"""
Media Create GUI - Main FastAPI Application
AI多模态内容生成平台主应用
"""

from contextlib import asynccontextmanager
import structlog
import uuid
from datetime import datetime
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
import os

# 导入核心模块
from .core.config import settings
from .core.database import init_db, check_db_connection
from .core.task_queue import task_queue
from .core.logging import setup_logging
from .core.cache import cache_manager

# 导入API路由
from .api.auth import router as auth_router
from .api.content import router as content_router
from .api.folders import router as folders_router
from .api.tags import router as tags_router
from .api.admin import router as admin_router
from .api.system import router as system_router

# 导入服务
from .services.health_check_service import health_check_service

# 配置结构化日志
logger = structlog.get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info(
        "应用启动中...", app_name=settings.app_name, version=settings.app_version
    )

    try:
        # 设置日志
        setup_logging()

        # 初始化数据库引擎
        logger.info("初始化数据库引擎...")
        from .core.database import init_database_engine
        
        # 优先使用环境变量中的DATABASE_URL，否则使用配置文件中的设置
        database_url = os.getenv("DATABASE_URL", settings.database.url)
        init_database_engine(database_url, settings.debug)

        # 初始化数据库
        logger.info("初始化数据库...")
        await init_db()

        # 检查数据库连接
        if await check_db_connection():
            logger.info("数据库连接正常")
        else:
            logger.error("数据库连接失败")
            raise RuntimeError("数据库连接失败")

        # 启动任务队列
        logger.info("启动任务队列...")
        await task_queue.start()

        # 初始化缓存系统
        logger.info("初始化缓存系统...")
        # 创建系统统计缓存（5分钟TTL，1000条最大容量）
        cache_manager.create_cache(
            "system_stats",
            default_ttl=300,
            max_size=1000,
            cleanup_interval=60
        )
        # 创建用户会话缓存（30分钟TTL，5000条最大容量）
        cache_manager.create_cache(
            "user_sessions",
            default_ttl=1800,
            max_size=5000,
            cleanup_interval=300
        )
        # 创建内容元数据缓存（10分钟TTL，2000条最大容量）
        cache_manager.create_cache(
            "content_metadata",
            default_ttl=600,
            max_size=2000,
            cleanup_interval=120
        )
        
        # 启动所有缓存
        await cache_manager.start_all()

        logger.info("应用启动完成")

    except Exception as e:
        logger.error("应用启动失败", error=str(e))
        raise

    yield

    # 关闭时
    logger.info("应用关闭中...")

    try:
        # 停止缓存系统
        logger.info("停止缓存系统...")
        await cache_manager.stop_all()

        # 停止任务队列
        logger.info("停止任务队列...")
        await task_queue.stop()

        logger.info("应用关闭完成")

    except Exception as e:
        logger.error("应用关闭失败", error=str(e))


# 创建FastAPI应用实例
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="AI多模态内容生成平台 - 支持文本生成图片、视频、音频等内容",
    lifespan=lifespan,
    docs_url="/docs" if settings.is_development else None,
    redoc_url="/redoc" if settings.is_development else None,
)

# 配置中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.security.cors_origins,
    allow_credentials=settings.security.cors_allow_credentials,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

app.add_middleware(GZipMiddleware, minimum_size=1000)


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    logger.error(
        "未处理的异常",
        error=str(exc),
        path=request.url.path,
        method=request.method,
        client_ip=request.client.host if request.client else "unknown",
    )

    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "error": {
                "code": "INTERNAL_SERVER_ERROR",
                "message": "服务器内部错误，请稍后重试",
                "request_id": str(uuid.uuid4()),
            },
        },
    )


# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查"""
    try:
        # 使用健康检查服务获取详细状态
        health_status = await health_check_service.get_health_status()
        
        # 根据总体健康状态设置HTTP状态码
        status_code = 200 if health_status.get("overall_health", False) else 503
        
        return JSONResponse(status_code=status_code, content=health_status)
        
    except Exception as e:
        logger.error("健康检查失败", error=str(e))
        return JSONResponse(
            status_code=503,
            content={
                "status": "unhealthy",
                "timestamp": datetime.now().isoformat(),
                "error": str(e),
                "overall_health": False,
            },
        )


# 详细健康检查端点
@app.get("/health/detailed")
async def detailed_health_check():
    """详细健康检查"""
    try:
        # 获取详细健康报告
        detailed_report = await health_check_service.get_detailed_health_report()
        
        # 根据总体健康状态设置HTTP状态码
        status_code = 200 if detailed_report.get("overall_health", False) else 503
        
        return JSONResponse(status_code=status_code, content=detailed_report)
        
    except Exception as e:
        logger.error("详细健康检查失败", error=str(e))
        return JSONResponse(
            status_code=503,
            content={
                "status": "unhealthy",
                "timestamp": datetime.now().isoformat(),
                "error": str(e),
                "overall_health": False,
            },
        )


# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "欢迎使用 Media Create GUI - AI多模态内容生成平台",
        "version": settings.app_version,
        "docs": "/docs" if settings.is_development else "API文档已禁用",
        "health": "/health",
    }


# 包含API路由
app.include_router(auth_router, prefix="/api/v1/auth", tags=["认证"])
app.include_router(content_router, prefix="/api/v1/content", tags=["内容管理"])
app.include_router(folders_router, prefix="/api/v1/folders", tags=["文件夹管理"])
app.include_router(tags_router, prefix="/api/v1/tags", tags=["标签管理"])
app.include_router(admin_router, prefix="/api/v1/admin", tags=["系统管理"])
app.include_router(system_router, prefix="/api/v1/system", tags=["系统管理"])

# 导出应用实例
__all__ = ["app"]
